﻿using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using DbManager;
using DbManager.DataManager;
using DbManager.QueryBuilder.DbEntity.IND.BazaOtdiha;
using DbManager.QueryBuilder.DbEntity.IND.Uslovia;
using DbManager.QueryBuilder.DbEntity.Komnata;
using DbManager.QueryBuilder.DbEntity.Pol;
using TAProject.UI.Order;

namespace TAProject.UI.Service.Price
{
    public partial class FormManagePol : FormTemplate
    {
        private readonly Form _parentForm;
        private readonly IDataManager _dataManager;
        private readonly IConnectionManager _connectionManager;
        private readonly AEntityPol _aEntityPol;

        private int _currentRowIndex;
        private int _napravlenieId;
        private int _gorodId;
        private DataTable _dataTableMain;

        public FormManagePol(Form parentForm, IDataManager dataManager, IConnectionManager connetctionManager)
            : base(parentForm)
        {
            InitializeComponent();

            _parentForm = parentForm;
            _dataManager = dataManager;
            _connectionManager = connetctionManager;

            _aEntityPol = new EntityPol();

            comboBoxNapravlenie.SelectedValueChanged += ComboBoxNapravlenieSelectedValueChanged;
            comboBoxGorod.SelectedValueChanged += ComboBoxGorodSelectedValueChanged;
            checkBoxShowAll.CheckedChanged += CheckBoxShowAllCheckedChanged;

            UpdateDataGrid();

            _parentForm.Enabled = false;
        }

        private void FormManagePot_EnabledChanged(object sender, EventArgs e)
        {
            if (dataGridView.Rows.Count > 0)
                dataGridView.Rows[_currentRowIndex].Selected = true;
        }

        private void DataGridViewCellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex < 0) return;
            _currentRowIndex = e.RowIndex;
        }

        #region Buttons evens

        private void ButtonAddClick(object sender, EventArgs e)
        {
            var formSelectItem = _gorodId != 0
                                     ? new FormSelectItem(this, new EntityBazaOtdiha(), _dataManager, _connectionManager,
                                                          "Выберите базу отдыха", _gorodId, "Hide_IDGorod")
                                     : new FormSelectItem(this, new EntityBazaOtdiha(), _dataManager, _connectionManager,
                                                          "Выберите базу отдыха");
            formSelectItem.ShowDialog(this);
            if (formSelectItem.Id == null || formSelectItem.Id == 0) return;
            _aEntityPol.IDBazaOtdiha = formSelectItem.Id.Value;

            formSelectItem = new FormSelectItem(this, new EntityKomnata(), _dataManager, _connectionManager,
                                                "Выберите тип комнаты");
            formSelectItem.ShowDialog(this);
            if (formSelectItem.Id == null || formSelectItem.Id == 0) return;
            _aEntityPol.IDKomnata = formSelectItem.Id.Value;

            formSelectItem = new FormSelectItem(this, new EntityUslovia(), _dataManager, _connectionManager,
                                                "Выберите условия");
            formSelectItem.ShowDialog(this);
            if (formSelectItem.Id == null || formSelectItem.Id == 0) return;
            _aEntityPol.IDUslovia = formSelectItem.Id.Value;

            var formPrice = new FormPrice(this);
            formPrice.ShowDialog(this);
            if (formPrice.Price == null || formPrice.Price == 0) return;
            _aEntityPol.Price = formPrice.Price.Value;

            var rowAffected = _dataManager.ManageDataInDb(_aEntityPol.GetInsertQuery(),
                                                          _connectionManager.GetConnection());
            _currentRowIndex = 0;
            dataGridView.Rows[_currentRowIndex].Selected = true;
            if (rowAffected == 0)
                MessageBox.Show("Ошибка добавления данных");
            else
                UpdateDataGrid();
        }

        private void ButtonEditClick(object sender, EventArgs e)
        {
            if (dataGridView.CurrentRow != null)
            {
                var currentRow = dataGridView.CurrentRow.Index;

                _aEntityPol.ID = (int) dataGridView.Rows[currentRow].Cells["Hide_IDPol"].Value;
                _aEntityPol.IDKomnata = (int) dataGridView.Rows[currentRow].Cells["Hide_IDKomnata"].Value;
                _aEntityPol.IDUslovia = (int) dataGridView.Rows[currentRow].Cells["Hide_IDUslovia"].Value;
                _aEntityPol.IDBazaOtdiha = (int) dataGridView.Rows[currentRow].Cells["Hide_IDBazaOtdiha"].Value;

                _aEntityPol.Price = (decimal) dataGridView.Rows[currentRow].Cells["Цена"].Value;

                var formPrice = new FormPrice(this, _aEntityPol.Price);
                formPrice.ShowDialog(this);
                if (formPrice.Price == null || formPrice.Price == 0) return;
                _aEntityPol.Price = formPrice.Price.Value;

                var rowAffected = _dataManager.ManageDataInDb(_aEntityPol.GetUpdateQuery(),
                                                              _connectionManager.GetConnection());
                _currentRowIndex = 0;
                dataGridView.Rows[_currentRowIndex].Selected = true;
                if (rowAffected == 0)
                    MessageBox.Show("Ошибка обновления данных");
                else
                    UpdateDataGrid();
            }
        }

        private void ButtonDeleteClick(object sender, EventArgs e)
        {
            if (dataGridView.CurrentRow != null)
            {
                _aEntityPol.ID = (int)dataGridView.Rows[_currentRowIndex].Cells["Hide_IDPol"].Value;
                //var str = _aEntityPol.GetDeleteQuery();
                var rowAffected = _dataManager.ManageDataInDb(_aEntityPol.GetDeleteQuery(),
                                                              _connectionManager.GetConnection());
                _currentRowIndex = 0;
                dataGridView.Rows[_currentRowIndex].Selected = true;
                if (rowAffected == 0)
                {
                    MessageBox.Show("Ошибка удаления, повторите попытку.");
                }
            }

            UpdateDataGrid();
        }

        private void ButtonCloseClick(object sender, EventArgs e)
        {
            FormClose();
        }

        private void FormClose()
        {
            _parentForm.Enabled = true;
            Close();
        }

        #endregion

        private void ComboBoxNapravlenieSelectedValueChanged(object sender, EventArgs e)
        {
            if (comboBoxNapravlenie.Items.Count < 1 || comboBoxNapravlenie.SelectedValue == null) return;
            _napravlenieId = (int) comboBoxNapravlenie.SelectedValue;
            var dataTableFilteredByNapavlenie = _dataTableMain.AsEnumerable().
                Where(row => row.Field<int>("Hide_IDNapravlenie") == _napravlenieId).CopyToDataTable();

            FillComboBoxFromDataTable(comboBoxGorod, dataTableFilteredByNapavlenie, "Hide_IDGorod", "Город");
            _gorodId = (int) comboBoxGorod.SelectedValue;
            var dataTableFilteredByGorod = _dataTableMain.AsEnumerable().
                Where(row => row.Field<int>("Hide_IDGorod") == _gorodId).CopyToDataTable();
            CustomFillDataGrid(dataTableFilteredByGorod);
        }

        private void ComboBoxGorodSelectedValueChanged(object sender, EventArgs e)
        {
            if (comboBoxGorod.Items.Count < 1 || comboBoxGorod.SelectedValue == null) return;
            _gorodId = (int) comboBoxGorod.SelectedValue;
            var dataTableFilteredByGorod = _dataTableMain.AsEnumerable().
                Where(row => row.Field<int>("Hide_IDGorod") == _gorodId).CopyToDataTable();
            CustomFillDataGrid(dataTableFilteredByGorod);
        }

        private void CheckBoxShowAllCheckedChanged(object sender, EventArgs e)
        {
            buttonAdd.Enabled = !checkBoxShowAll.Checked;
            FillDataGrid();
        }

        private void FillComboBoxFromDataTable(ListControl comboBox, DataTable dataTable, string valueMember,
                                                      string displayMember)
        {
            comboBoxNapravlenie.SelectedValueChanged -= ComboBoxNapravlenieSelectedValueChanged;
            comboBoxGorod.SelectedValueChanged -= ComboBoxGorodSelectedValueChanged;

            comboBox.DataSource = dataTable.AsEnumerable().
                Distinct(new DataTableComparer(displayMember)).
                CopyToDataTable().DefaultView;
            comboBox.ValueMember = valueMember;
            comboBox.DisplayMember = displayMember;

            comboBoxNapravlenie.SelectedValueChanged += ComboBoxNapravlenieSelectedValueChanged;
            comboBoxGorod.SelectedValueChanged += ComboBoxGorodSelectedValueChanged;

        }

        private void UpdateDataGrid()
        {
            if (_connectionManager.CheckConnection())
            {
                _dataTableMain = _dataManager.GetDataTable(_aEntityPol.GetSelectQuery(),
                                                           _connectionManager.GetConnection());
                if (_dataTableMain != null)
                {
                    FillDataGrid();
                    _currentRowIndex = 0;
                }
                else
                {
                    MessageBox.Show("Данные отсутствуют.");
                }
            }
            else
            {
                MessageBox.Show("Ошибка подключения к БД.");
                FormClose();
            }
        }

        private void FillDataGrid()
        {
            if (_dataTableMain.Rows.Count > 0)
            {
                buttonDelete.Enabled = true;
                buttonEdit.Enabled = true;
                checkBoxShowAll.Enabled = true;
                comboBoxNapravlenie.Enabled = true;
                comboBoxGorod.Enabled = true;

                if (checkBoxShowAll.Checked)
                {
                    comboBoxNapravlenie.Enabled = false;
                    comboBoxGorod.Enabled = false;
                    _gorodId = 0;
                    _napravlenieId = 0;
                    CustomFillDataGrid(_dataTableMain);
                }
                else
                {
                    comboBoxNapravlenie.Enabled = true;
                    comboBoxGorod.Enabled = true;
                    
                    FillComboBoxFromDataTable(comboBoxNapravlenie, _dataTableMain, "Hide_IDNapravlenie", "Направление");
                    _napravlenieId = (int) comboBoxNapravlenie.SelectedValue;
                    var dataTableFilteredByNapavlenie = _dataTableMain.AsEnumerable().
                        Where(row => row.Field<int>("Hide_IDNapravlenie") == _napravlenieId).CopyToDataTable();

                    FillComboBoxFromDataTable(comboBoxGorod, dataTableFilteredByNapavlenie, "Hide_IDGorod", "Город");
                    _gorodId = (int) comboBoxGorod.SelectedValue;
                    var dataTableFilteredByGorod = _dataTableMain.AsEnumerable().
                        Where(row => row.Field<int>("Hide_IDGorod") == _gorodId).CopyToDataTable();
                    CustomFillDataGrid(dataTableFilteredByGorod);
                }
            }
            else
            {
                buttonDelete.Enabled = false;
                buttonEdit.Enabled = false;
                checkBoxShowAll.Enabled = false;
                comboBoxNapravlenie.Enabled = false;
                comboBoxGorod.Enabled = false;
                comboBoxNapravlenie.DataSource = null;
                comboBoxGorod.DataSource = null;
                CustomFillDataGrid(_dataTableMain);
                MessageBox.Show("Данные отсутствуют");
            }
        }

        private void CustomFillDataGrid(DataTable dataTable)
        {
            if (dataTable != null)
            {
                //dataTable.Columns["Количество мест"].ColumnName = "Мест";
                dataGridView.DataSource = dataTable;
                //скрываем все ненужные столбцы
                for (var i = 0; i < dataGridView.Columns.Count; i++)
                {
                    if (dataGridView.Columns[i].Name.StartsWith("Hide"))
                    {
                        dataGridView.Columns[i].Visible = false;
                    }
                }
            }
            else
            {
                MessageBox.Show("Данные отсутствуют.");
            }
        }
    }
}